package com.snake.mylibrary.mina;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;

import com.snake.mylibrary.utils.LogUtil;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.lang.ref.WeakReference;
import java.net.InetSocketAddress;

public class ConnectionManager {
    private ConnectionConfig mConfig;
    private WeakReference<Context> mContext;
    private NioSocketConnector mConnector;
    private IoSession mSession;
    private InetSocketAddress mAddress;

    public ConnectionManager(ConnectionConfig config){
        mConfig = config;
        mContext = new WeakReference<Context>(config.getContext());
        init();

    }

    private void init() {
        mAddress = new InetSocketAddress(mConfig.getIp(),mConfig.getPort());
        mConnector = new NioSocketConnector();
        mConnector.setDefaultRemoteAddress(mAddress);
        mConnector.getSessionConfig().setReadBufferSize(mConfig.getReadBufferSize());
        mConnector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE,mConfig.getConnectionTimeout());
        mConnector.getFilterChain().addLast("logging",new LoggingFilter());
        mConnector.getFilterChain().addLast("codec",new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
        mConnector.setHandler(new DefaultHandler(mContext.get()));
    }

    /**
     * 外层调用取得与服务器的链接
     * @return
     */
    public boolean connect(){
        LogUtil.e("connect");
        try{
            ConnectFuture future = mConnector.connect();
            future.awaitUninterruptibly();
            mSession = future.getSession();
            SessionManager.getInstance().setSession(mSession);
        }catch (Exception e){
            return false;
        }
        return mSession!=null;
    }

    /**
     * 外界调用断开连接
     */
    public void disConnection(){
        mConnector.dispose();
        mConnector = null;
        mSession = null;
        mAddress = null;
        mContext = null;
    }



    private static final class DefaultHandler extends IoHandlerAdapter{
        private static final String MINA_BROADCAST_ACTION = "com.snake.mylibrary.mina";
        private static final String MESSAGE = "message";
        private Context mContext;
        DefaultHandler(Context context){
            mContext = context;
        }

        @Override
        public void sessionOpened(IoSession session) throws Exception {
            super.sessionOpened(session);
            //
        }

        @Override
        public void messageReceived(IoSession session, Object message) throws Exception {
            super.messageReceived(session, message);
            if(mContext!=null){
                Intent intent = new Intent(MINA_BROADCAST_ACTION);
                intent.putExtra(MESSAGE,message.toString());
                LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
            }
            //在这里可以实现接收服务器的数据，来进行通知消息。
        }
    }

}
